package com.starryx.sim.mvc.net.handler;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AsciiString;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetSocketAddress;


public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

	private static final Logger log = LogManager.getLogger(HttpServerHandler.class);

	private static final AsciiString CONNECTION = AsciiString.cached("Connection");

	private static final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive");

	private static final AsciiString CONTENT_TYPE = AsciiString.cached("Content-Type");

	private static final AsciiString CONTENT_LENGTH = AsciiString.cached("Content-Length");

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
		String uri = fullHttpRequest.uri();
		RequestHandler requestHandler = RequestHandlerFactory.create(fullHttpRequest.method());
		requestHandler.handle(fullHttpRequest, channelHandlerContext);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		log.error("{}", cause.getMessage());
		ctx.close();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
		log.info("客户端连接成功，ip：{}", inetSocketAddress.getAddress().getHostAddress());
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		super.channelUnregistered(ctx);
		if (ctx.channel().isActive()) {
			ctx.close();
		}
		InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
		log.info("客户端连接断开，ip：{}", inetSocketAddress.getAddress().getHostAddress());
	}

}
